const Answer = require('../models/ansawer')

class AnswerCtl{
    async find(ctx){
        let {limit=5} = ctx.query.limit 
        limit = Math.max(limit * 1, 1)
        const page = Math.max(ctx.query.page * 1 -1, 0)
        const q = new RegExp(ctx.query.q)
        ctx.body = await Answer.find({content: q, questionId: ctx.params.questionId}).limit(limit).skip(page*limit)
    }

    async findById(ctx){
        const {fields} = ctx.query
        const SelectFields = fields.split(';').fitler(f=>f).map(f => '+' + f).join('')
        const answer = await Answer.findById(ctx.params.id).select(SelectFields).populate('answerer')
        if(!answer) ctx.throw(404, '问题不存在')
        ctx.body = answer
    }

    async create(ctx){
        // const {username} = ctx.request.body
        // let user = await User.findOne({username})
        // if(user) ctx.throw(409, '用户名已存在')
        const topic = await new Topic(ctx.request.body).save()
        ctx.body = topic
    }

    async update(ctx){
        await  ctx.state.question.update(ctx.request.body)
        ctx.body = ctx.state.question
    }

    async checkQuestioner(ctx, next){
        const {question } = ctx.state
        if(question.questioner.toString() !== ctx.state.user._id) ctx.throw(403, '没有权限')
        await next()
    }
    async delete(ctx){
        ctx.status = 204
        await Question.findByIdAndRemove(ctx.params.id)
        // ctx.body = {}
    }

    async listFollowing(ctx){
        const user = await User.findById(ctx.params.id).select('+following').populate('following')
        if (!user) ctx.throw(404)
        ctx.body = user.following
    }

    async listTopicFollowers(ctx){
        const users = await User.find({followingTopics: ctx.params.id})
        ctx.body  = users
    }


    // 检查答案是否存在中间件
    async checkAnsawerExist(ctx, next){
        const answer = Answer.findById(ctx.params.id).select('+answerer')
        if(!answer) ctx.throw(404, '答案不存在')
        if(answer.questionId !== ctx.params.questionId) ctx.throw(404, '该问题下没有此答案')
        // ctx.state.answer = answer
        await next()
    }

    async follow(ctx){
        const me = await User.findById(ctx.state.user._id).select('+following')
        if(!me.following.map(id=>id.toString()).includes(ctx.params.id)){
            me.following.push(ctx.params.id).save()
        }
        ctx.status = 204         
    }

    async unfollow(ctx){
        const me = await User.findById(ctx.state.user._id).select('+following')
        const index = me.following.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.following.splice(index, 1).save()
        }
        ctx.status = 204       
    }
}

module.exports = new AnswerCtl()